package com.example.demo.listener;

import com.example.demo.Entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletContext;
import java.util.concurrent.ConcurrentHashMap;


@WebListener
public class LogoutUserListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // 无需处理session创建事件
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        Object userObj = session.getAttribute("USER");

        if (userObj instanceof User) {
            User logoutUser = (User) userObj;
            ServletContext application = session.getServletContext();

            synchronized (application) {
                ConcurrentHashMap<Integer, User> onlineUsers =
                    (ConcurrentHashMap<Integer, User>) application.getAttribute("ONLINE_USER");

                if (onlineUsers != null && !onlineUsers.isEmpty()) {
                    // 通过用户ID移除在线用户
                    onlineUsers.remove(logoutUser.getUserId());
                    application.setAttribute("ONLINE_USER", onlineUsers);
                }
            }
        }
    }
}
